// console.log("thin3");

import thin_render from "./lib/thin_render.mjs";
import thin_pop, { popclose } from "./lib/thin_pop.mjs";
import { after, clearafterqueue } from "./lib/delay_render.mjs";
import thin_ajax from "./lib/thin_ajax.mjs";
import { alert, confirm, dialog } from "./lib/dialog.mjs";
import { datalist } from "./lib/datalist.mjs";
import template_extend from "./lib/ext_template.mjs";
import validate from "./lib/validate.mjs";
import viewmode from "./lib/viewmode.mjs";
import { docCookies } from "./lib/cookies.mjs";
import { thin_fetch } from "./lib/thin_fetch.mjs";
import { thin_poplayer } from "./lib/thin_poplayer.mjs";
import datahelper from "./helper/datahelper.mjs";
import render_helper from "./lib/render_helper.mjs";
import { nearest_data, nearest_render } from "./lib/nearest.mjs";

/**
 * thin 核心函数 - 类似 jQuery 的选择器函数
 * 支持三种调用方式:
 * 1. thin(undefined) - 返回 undefined
 * 2. thin(function) - DOM ready 回调函数
 * 3. thin(selector, context) - 选择器查询，context默认为document
 */
function thin(selector, context = document) {
  // console.log("thin3");

  // 支持三种调用方式:
  // 1. thin(undefined) - 返回 undefined
  // 2. thin(function) - DOM ready 回调
  // 3. thin(selector) - 选择器查询
  if (selector === undefined) {
    return;
  } else if (typeof selector === "function") {
    return thin.ready(selector);
  } else {
    // function select() {
    let elements;
    if (typeof selector === "string") {
      // 如果 context 是字符串，先查找 context 元素，再在其中查找 selector
      if (typeof context === "string") {
        elements = document.querySelector(context).querySelectorAll(selector);
      } else {
        // 在指定上下文中查找元素
        elements = context.querySelectorAll(selector);
      }
    } else if (selector.nodeType) {
      // 如果是 DOM 节点，直接包装
      elements = [selector];
    } else if (selector.length) {
      // 如果是类数组对象（如 NodeList），直接使用
      elements = selector;
    }
    // 返回包含 DOM 操作方法的对象
    return { ...fn, ...{ nodelist: elements } };
    // return { ...fn, ...elements };
    // return Object.assign(elements, fn);
  }
}

// import { render } from "./lib/render.mjs";

// thin.render = render;

/**
 * 核心方法集合，会被附加到选择器返回的对象上
 * 包含DOM操作、渲染等基础功能
 */
let fn = {
  // render: 渲染模板
  render: function (template, data) {
    this.each((node) => {
      // 如果提供了数据，保存到节点上
      if (data !== undefined) {
        node.thin_data = data;
      }
      // 保存模板并创建渲染函数
      node.thin_template = template;
      node.thin_render = function () {
        thin_render(node, node.thin_template);
      };
      node.thin_render();
    });
    clearafterqueue();
    return this;
  },

  // rerender: 重新渲染
  rerender: function () {
    this.each((node) => {
      if (node.thin_render) {
        thin(node).empty();
        console.log(node);
        console.log(node.thin_render);
        node.thin_render();
      }
    });
    clearafterqueue();
    return this;
  },

  // DOM 操作方法
  each: function (callback) {
    this.nodelist.forEach((node) => {
      callback(node);
    });
    return this;
  },

  // 清空节点内容
  empty: function () {
    this.nodelist.forEach((node) => {
      node.innerHTML = "";
      // 注释掉的是另一种清空方式
      // while (node.firstChild) {
      //   node.removeChild(node.firstChild);
      // }
    });
    return this;
  },

  // 从 DOM 中移除节点
  remove: function () {
    this.nodelist.forEach((node) => {
      node.parentNode.removeChild(node);
    });
  },
  attr: function (attribute, value) {
    this.nodelist.forEach((node) => {
      node.setAttribute(attribute, value);
    });
    return this;
  },
  on: function (event, fn) {
    this.each((node) => {
      node.addEventListener(event, fn);
    });
    return this;
  },
  removeClass: function (classname) {
    this.each((node) => {
      node.classList.remove(classname);
    });
    return this;
  },
  addClass: function (classname) {
    this.each((node) => {
      node.classList.add(classname);
    });
    return this;
  },
};

let onready = [];

/**
 * 工具方法集合，直接挂载在thin对象上
 */
// 序列化对象为query string
thin.serialize = function (obj) {
  let arr = [];
  for (let key in obj) {
    arr.push(
      key +
        "=" +
        (typeof obj[key] == "object" ? JSON.stringify(obj[key]) : obj[key])
    );
  }
  return arr.join("&");
};

/**
 * 重新渲染
 * @param {*} sender
 * @returns
 */
thin.rerender = function (sender) {
  console.log({ sender });
  let container = nearest_render(sender);
  console.log({ container });
  if (container) {
    thin(container).rerender();
  }
};

/**
 * DOM ready事件处理
 * 将回调函数存入onready数组，等待DOM加载完成后执行
 */
thin.ready = function (fn) {
  onready.push(fn);
};

/**
 * 扩展功能挂载
 * 将各种独立模块的功能挂载到thin对象上
 */
thin.pop = thin_pop; // 弹出层
thin.poplayer = thin_poplayer; // 弹出层扩展
thin.popclose = popclose; // 关闭弹出层
thin.confirm = confirm; // 确认对话框
thin.alert = alert; // 提示对话框
thin.dialog = dialog; // 自定义对话框
thin.after = after; // 延迟渲染
thin.clearafterqueue = clearafterqueue; // 清理渲染队列
thin.datalist = datalist; // 数据列表组件
thin.render = thin_render; // 渲染引擎
thin.template_extend = template_extend; // 模板扩展
thin.validate = validate; // 数据验证
thin.viewmode = viewmode; // 视图模式
thin.cookies = docCookies; // Cookie操作

/**
 * 生成唯一标识符
 * 利用Blob URL生成唯一字符串
 * @returns {string} 唯一标识符
 */
thin.uuid = function () {
  let url = URL.createObjectURL(new Blob());
  URL.revokeObjectURL(url);
  return url.substring(url.lastIndexOf("/") + 1);
};

thin.ajax = thin_ajax; // AJAX请求
thin.fetch = thin_fetch; // Fetch请求

thin.datahelper = datahelper; // 数据处理助手
thin.render_helper = render_helper; // 渲染助手
thin.nearest_data = nearest_data; // 就近数据获取

/**
 * DOM Ready事件处理
 * 当页面加载完成时，按顺序执行所有注册的回调函数
 */
window.addEventListener("load", (ev) => {
  while (onready.length) {
    onready.shift()();
  }
});

export { thin };
